package com.hns.can.common.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.constants.GlobalConst;
import com.hns.can.common.service.CacheTaskManager;
import com.hns.tool.pub.ContextHolderUtils;

/**
 * 缓存控制器
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
@Controller
public class SysCacheController extends BaseController{
	@Autowired
	private CacheTaskManager cacheTaskManager;
	
	/**
	 * 清除缓存，尽量避免直接调用（主要用于数据库数据被直接修改时的服务器缓存同步）
	 * @param key
	 * @return
	 * @throws Exception
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
	/*@RequestMapping(value = "/system/cache/evict")
	@CacheEvict(value = GlobalConst.SYSTEM_CACHE_NAME, key = "#key", beforeInvocation=true)
	@ResponseBody
	public Object evict(@RequestParam(required=true) String key) throws Exception {
		return getReturnResult();
	}*/
	
	/**
	 * 根据类别获取缓存
	 * @param codes    缓存的code
	 * @return 缓存列表
	 * @throws Exception
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
	@RequestMapping(value = "/system/cache/codes")
	@ResponseBody
	public Object codes(@RequestParam("codes") List<String> codes) throws Exception {
	    
	    HttpServletRequest request = ContextHolderUtils.getRequest();
        SysUserEntity user = (SysUserEntity)request.getSession().getAttribute("SES_CURRENTUSER");
		Map<String, Object> result = new HashMap<String, Object>();
		for (String key : codes) {
		    Object value = cacheTaskManager.loadCache(key, user.getCorpId());
            if(GlobalConst.CACHE_KEY_SYS_CODE.equals(key) && value!=null){
                result.putAll((Map<? extends String, ? extends Object>) value);
            }else{
                result.put(key, value);
            }
		}
		return getReturnResult(result);
	}
	
}
